<?php

namespace backend\models;

use Yii;
use backend\helpers\FileNameInflector;
use yii\web\UploadedFile;

/**
 * This is the model class for table "contract_file".
 *
 * @property int $id
 * @property string $title
 * @property string $filename
 * @property int $id_contract
 *
 * @property Contract $contract
 */
class ContractFile extends \yii\db\ActiveRecord
{
    const BUCKET_NAME = 'ogikm-contracts';
    //const BUCKET_NAME = 'ogikm-test';

    public $file;
    public $contractOwnNumber;
    public $contractRegistryNumber;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'contract_file';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'id_contract', 'file', 'contractOwnNumber', 'contractRegistryNumber'], 'required'],
            [['id_contract'], 'integer'],
            [['title'], 'string', 'max' => 512],
            [['filename'], 'string', 'max' => 255],
            [['id_contract'], 'exist', 'skipOnError' => true, 'targetClass' => Contract::className(), 'targetAttribute' => ['id_contract' => 'id']],
            [['file'], 'file', 'extensions' => 'doc, docx, pdf, zip', 'maxSize' => 1024*1024*150],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Название документа',
            'file' => 'Документ',
            'filename' => 'Filename',
            'id_contract' => 'Id Contract',
        ];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }
        // Запись новая
        if($insert)
        {
            // Спокойно сохраняем все файлы
            $this->insertFile();
        }
        // Запись обновляется
        else
        {
            // Необходимы дополнительные проверки
            $this->insertFile();
        }
        
        return true;
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteFile($this->filename);

        return true;
    }

    /**
     * Gets query for [[Contract]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getContract()
    {
        return $this->hasOne(Contract::className(), ['id' => 'id_contract']);
    }

    private function insertFile()
    {
        if($this->file)
        {
            $this->filename = $this->uploadFile($this->file, $this->generateFileName());
        } 
    }

    private function uploadFile($file, $fileName)
    {
        $fileName = $fileName . '.' . $file->extension;

        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
            return $fileName;
        }
        else 
        {
            return null;
        }
    }

    private function deleteFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }

    private function generateFileName()
    {
        return 'Договор №' . FileNameInflector::specialSlug($this->contractOwnNumber) 
        . ' (' . $this->contractRegistryNumber . ')' 
        . ' - ' . $this->title 
        . ' (' . uniqid() . ')';
    }
}
